<?php
import("com.yamvc.render.ITemplate");
import("com.miho.exceptions.NullPointerException");
class Template implements ITemplate {
	private $_vars=array();
	private $_engine;
	private $_path;
	private $_parent;
	private $_name;
	public function getPath(){
		return $this->_path;
	}
	public function setEngine(IEngine $engine){
		$this->_engine = $engine;
	}
	public function putVariable($key,$variable){
		$this->_vars[$key] = $variable;
		if ($variable instanceof ITemplate) {
			$variable->setName($key);
		}
		
	}
	public function setParent(ITemplate $parent){
		$this->_parent = $parent;
		if ($this->_name!=""){
			$this->_parent->putVariable($this->_name,$this);
			//var_dump($this->_name);
		}
	}
	public function getParent(){
		return $this->_parent;
	}
	public function getName(){
		return $this->_name;
	}
	public function setName($name){
		$this->_name = $name;
	}
	public function __get($name){
		if(!isset($this->_vars[$name])){
			return null;
			//throw new NullPointerException();
		}
		return $this->_vars[$name];
	}
	public function render(){
		$res="";
		if (Application::getAppInstance()->useAjax()){
			$res="<yamvc:template>"; 
		}
		ob_start();
		 include $this->getPath();
		 $res.=ob_get_clean();
		 if (Application::getAppInstance()->useAjax()){
		 	$res.="</yamvc:template>";
		 }
		 return $res;		 
	}
	
	public function getScriptPath(){
		return Application::getAppInstance()->getScriptPath();
	}
	
	public function getImagesPath(){
		return Application::getAppInstance()->getImagesPath();
	}
	
	public function getStylesPath(){
		return Application::getAppInstance()->getStylesPath();
	}
	
	public function __construct($path,$name=""){
		$this->_path = $path;
		$this->_name = $name;
	}
	
	public function __toString(){
		return $this->render();
	}
	
	public function createUrl($name,$action=null,$event=null,$eventType=null,$params=null){
		if(Application::getAppInstance()->useAjax()==Application::AJAX_ON){
			$url="javascript:";
		}else{
			$url = Application::getAppInstance()->getBaseDir();
			if($action!=null){
				$url.=$action."/";
			}
			if($event!=null){
				$url.=$event."/";
			}
			if ($eventType!=null) {
				$url.=$eventType."/";
			}
			if (is_array($params)){
				foreach ($params as $p){
					$url.=$p."/";
				}
			}
		}
		$this->putVariable($name,$url);
		return $url;
	}
	
	public function __call($name,$arguments){
		$name[0] = strtoupper($name[0]);
		$class = $name."Helper";
        $helper = View::instance()->getHelper($class);
        var_dump($name);
		return call_user_func_array(
				array($helper,$name),
				$arguments
				);
	}
	
}

?>